#coding:utf-8

import math
import json
def scut(m,cnt=30):
    #print json.dumps(m,ensure_ascii=False) 
    n = [(u,v) for u,v in m.items() if len(u) > 1]
    n.sort(key = lambda x : -x[1])
    if len(n) > cnt:
        n = n[:cnt]
    return n

def norm(m):
    s = 0.0
    for v in m.values():
        s += v*v
    s = math.sqrt(s)
    x = {}
    for v,c in m.items():
        x[v] = c/s
    return x

def tcut(m,title):
    n = [(u,v) for u,v in m.items() if u in title]
    n.sort(key = lambda x : -x[1])
    return n

def get_sim_score(v1,v2):
    nn = 30
    v1 = scut(v1,nn)
    v2 = scut(v2,nn)

    v1 = {u:v for u,v in v1}
    v2 = {u:v for u,v in v2}

    sim = cos(v1,v2)
    return sim


def get_sim(v1,v2):
    #print len(v1),len(v2)
    nn = 30
    v1 = scut(v1,nn)
    v2 = scut(v2,nn)
    #v1 = tcut(v1,r1['TITLE'].lower())
    #v2 = tcut(v2,r2['TITLE'].lower())
    
    cc = 5
    n1 = min(cc,len(v1))
    n2 = min(cc,len(v2))
    print json.dumps(v1[:n1],ensure_ascii=False)
    print json.dumps(v2[:n2],ensure_ascii=False)

    v1 = {u:v for u,v in v1}
    v2 = {u:v for u,v in v2}

    sim = cos(v1,v2)
    return sim


def cos(m1,m2):
    s1 = 0.00001
    s2 = 0.00001
    s = 0
    for v in m1.values():
        s1 += v*v
    s1 = math.sqrt(s1)
    for v in m2.values():
        s2 += v*v
    s2 = math.sqrt(s2)
    for u,v1 in m1.items():
        v2 = m2.get(u,0)
        s += v1*v2
    return s/(s1*s2)



